import { PartFigure } from './PartFigure';
import { Stud } from '../model/Stud';
import { Canvas, PPM } from './Canvas';
import { FigureBase } from './FigureBase';

export const PortRadius = 1.6

export class StudFigure extends FigureBase {

    public canvas: Canvas
    public set: raphaeljs.Set
    public port?: raphaeljs.Element
    public name?: raphaeljs.Element

    constructor(public partFigure: PartFigure, public stud: Stud) {
        super("stud", stud)
        this.canvas = partFigure.canvas
        this.removable = false

        stud.figure = this

        this.set = this.canvas.paper.set()
                        
        if(stud.info.type!='none') {
            
            this.name = this.canvas.paper.text(0, 0, this.stud.info.title || this.stud.info.name)
            let {height: txtheight} = this.name?.getBBox() as raphaeljs.BBox2
            this.name?.attr({
                x: 4*PPM ,
                y: 7.9*PPM - txtheight/2 ,
                fill: this.stud.info.textColor || "#ffffff" ,
                'font-size': 1.5*PPM
            })
            this.set.push(this.name as raphaeljs.Element)

            this.port = this.canvas.paper.circle(4*PPM, 4*PPM, PortRadius*PPM, PortRadius*PPM, 1)
                                        .attr({fill:"#fff"})
            ; (this.port as any)[0].studFigure = this  // 在svg元素上记录自己

            this.set.push(this.port as raphaeljs.Element)
            this.canvas.portDragHandle?.setupPort(this)
            this.selector.setup(this.port as raphaeljs.Element)
        }
    }

    public portPosition() {
        if(!this.port) {
            console.error("StudFigure.port is null", this)
            return {x:0, y: 0}
        }
        let bbox = this.port.getBBox()
        let radius = this.port.attr("r")
        return {x: bbox.x+radius, y: bbox.y+radius}
    }

    public hittest(x: number, y: number, radius: number): boolean {
        if(!this.port)
            return false
        let {x:sx,y:sy} = this.portPosition()
        let dx = x-sx
        let dy = y-sy
        return Math.sqrt(dx*dx+dy*dy) < radius
    }

    public remove() {
        this.port && this.port.remove()
        this.set && this.set.remove()

        if(this.stud && this.stud.figure==this) {
            ; (this.stud.figure as any) = null
            ; (this.stud as any) = null
        }
    }

}